/*
 * Copyright (C) 2017 zhouyou(478319399@qq.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.randb.easyhttp.interceptor;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

import okhttp3.Connection;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.http.HttpHeaders;


/**
 * <p>描述：设置日志拦截器</p>
 * 提供了详细、易懂的日志打印<br>
 * 作者： zhouyou<br>
 * 日期： 2016/12/19 16:35<br>
 * 版本： v2.0<br>
 */
public class HttpLoggingInterceptor implements Interceptor {


    private static final Charset UTF8 = Charset.forName("UTF-8");

    private volatile Level level = Level.NONE;

    private Logger logger;

    private String tag;

    private boolean isLogEnable = false;

    public void log(String message) {
        logger.log(java.util.logging.Level.INFO, message);
    }

    public HttpLoggingInterceptor(String tag) {
        this.tag = tag;
        logger = Logger.getLogger(tag);
    }

    public HttpLoggingInterceptor(String tag, boolean isLogEnable) {
        this.tag = tag;
        this.isLogEnable = isLogEnable;
        logger = Logger.getLogger(tag);
    }

    public Level getLevel() {
        return level;
    }

    public HttpLoggingInterceptor setLevel(Level level) {
        if (level == null) throw new NullPointerException("level == null. Use Level.NONE instead.");
        this.level = level;
        return this;
    }


    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {

        Request request = chain.request();
        if (level == null) {
            return chain.proceed(request);
        }

        logForRequest(request, chain.connection());

        long startNs = System.nanoTime();
        Response response;

        response = chain.proceed(request);
        long tookNs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);


        return logForResponse(response, tookNs);
    }

    private Response logForResponse(Response response, long tookNs) {
        log("-------------------------------response-------------------------------");
        Response.Builder builder = response.newBuilder();
        Response clone = builder.build();
        ResponseBody responseBody = clone.body();
        boolean logBody = (level == Level.BODY);
        boolean logHeaders = (level == Level.BODY || level == Level.HEADERS);

        try {
            log("<-- " + clone.code() + ' ' + clone.message() + ' '
                    + URLDecoder.decode(clone.request().url().url().toString(),
                    UTF8.name()) + " (" + tookNs + "ms）");
            if (logHeaders) {
                log(" ");
                Headers headers = clone.headers();
                for (int i = 0, count = headers.size(); i < count; i++) {
                    log("\t" + headers.name(i) + ": " + headers.value(i));
                }
                log(" ");
                if (logBody && HttpHeaders.hasBody(clone)) {
                    if (isPlainText(responseBody.contentType())) {
                        String body = responseBody.string();
                        log("\tbody:" + body);
                        responseBody = ResponseBody.create(responseBody.contentType(), body);
                        return response.newBuilder().body(responseBody).build();
                    } else {
                        log("\tbody: maybe [file part] , too large too print , ignored!");
                    }
                }
                log(" ");
            }
        } catch (Exception e) {
            e(e);
        } finally {
            log("<-- END HTTP");
        }
        return response;

    }

    private void logForRequest(Request request, Connection connection) {
        log("-------------------------------request-------------------------------");
        boolean logBody = (level == Level.BODY);
        boolean logHeaders = (level == Level.BODY || level == Level.HEADERS);
        RequestBody requestBody = request.body();
        boolean hasRequestBody = requestBody != null;
        Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;

        try {
            String requestStartMessage = "-->"
                    + request.method() + " "
                    + URLDecoder.decode(request.url().url().toString(), UTF8.name())
                    + " " + protocol;
            log(requestStartMessage);

            if (logHeaders) {
                Headers headers = request.headers();
                for (int i = 0; i < headers.size(); i++) {
                    log("\t" + headers.name(i) + ": " + headers.value(i));
                }

                if (logBody && hasRequestBody) {
                    if (isPlainText(requestBody.contentType())) {
                        bodyToString(request);
                    } else {
                        log("\tbody: maybe [file part] , too large too print , ignored!");
                    }
                }


            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void bodyToString(Request request) {
        try {

            final Request copy = request.newBuilder().build();
            final okio.Buffer buffer = new okio.Buffer();
            Charset charset = UTF8;
            copy.body().writeTo(buffer);
            MediaType contentType = copy.body().contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            String result = buffer.readString(charset);
            log("\tbody:" + URLDecoder.decode(replacer(result), UTF8.name()));

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private String replacer(String result) {
        String data = result;
        try {
            data = data.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
            data = data.replace("//+", "%2B");
            data = URLDecoder.decode(data, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return data;
    }

    private boolean isPlainText(MediaType mediaType) {
        if (mediaType == null) return false;
        if ("text".equals(mediaType.type())) {
            return true;
        }
        String subType = mediaType.subtype();
        subType = subType.toLowerCase();
        return subType.contains("x-www-form-urlencoded") ||
                subType.contains("json") ||
                subType.contains("xml") ||
                subType.contains("html");
    }


    public enum Level {
        NONE,       //不打印log
        BASIC,      //只打印 请求首行 和 响应首行
        HEADERS,    //打印请求和响应的所有 Header
        BODY        //所有数据全部打印
    }

    public void e(java.lang.Throwable t) {
        if (isLogEnable) t.printStackTrace();
    }
}